package com.fate.framework.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import java.util.*;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class TreeNodeDTO extends TreeNode {
  /** 前端需要 组装树使用 */
  @Schema(description = "子节点")
  private List<TreeNodeDTO> children;

  public static <T extends TreeNodeDTO> List<T> sortNodeItemList(List<T> nodeList) {
    return nodeList.stream()
        .sorted(
            Comparator.comparing(
                item -> item.getOrderNumber() == null ? Integer.MAX_VALUE : item.getOrderNumber()))
        .collect(Collectors.toList());
  }
  /**
   * @param nodeList 输入一个一般的node list
   * @param isSort 是否排序
   * @return 返回一个树状的node list（可能包含多个顶级节点所以是树）
   */
  public static <T extends TreeNodeDTO> List<T> buildTreeFromFlatList(
      List<T> nodeList, boolean isSort) {
    Map<Object, T> nodeId2Node =
        nodeList.stream().collect(Collectors.toMap(T::getId, item -> item));

    Iterator<T> it = nodeList.iterator();
    while (it.hasNext()) {
      T item = it.next();
      if (nodeId2Node.containsKey(item.getPid())) {
        // 获取当前记录父对象，并将当前对象添加到父对象
        nodeId2Node.get(item.getPid()).addChild(item);
        // 在列表中删除当前对象
        it.remove();
      }
    }
    if (isSort) {
      for (T node : nodeId2Node.values()) {
        if (node.getChildren() != null) {
          node.setChildren(sortNodeItemList(node.getChildren()));
        }
      }
      nodeList = sortNodeItemList(nodeList);
    }
    return nodeList;
  }

  public static <T extends TreeNodeDTO> List<T> buildTreeFromFlatList(List<T> nodeList) {
    return buildTreeFromFlatList(nodeList, true);
  }

  public void addChild(TreeNodeDTO child) {
    if (children == null) {
      children = new LinkedList<>();
    }
    children.add(child);
  }
}
